/*
Copyright 2024 The Kagent Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package version

import (
	"bytes"
	"fmt"
	"os/exec"
	"runtime"
	"strings"
	"time"
)

type BuildInfo struct {
	Version        string
	GitCommit      string
	CompileVersion string
	Date           string
}

func GetBuildInfo() BuildInfo {
	// version := "v1.0.0" // 应用程序版本号，这里是一个示例值
	version := GetGitTag()
	gitCommit := getGitCommitHash()
	compileVersion := runtime.Version()

	return BuildInfo{
		Version:        version,
		GitCommit:      gitCommit,
		CompileVersion: compileVersion,
		Date:           time.Now().Format("2006-01-02 15:04:05"),
	}
}

func Version() string {
	bi := GetBuildInfo()
	return bi.String()
}

// String returns information about the release.
func (bi BuildInfo) String() string {
	return fmt.Sprintf(`-------------------------------------------------------------------------------
NGINX Ingress controller
  Version:       	%v
  GitCommit:     	%v
  CompileVersion:	%v
  BuildDate:     	%v
-------------------------------------------------------------------------------
`, bi.Version, bi.GitCommit, bi.CompileVersion, bi.Date)
}

func getGitCommitHash() string {
	cmd := exec.Command("git", "rev-parse", "--short", "HEAD")
	output, err := cmd.Output()
	if err != nil {
		return "UNKNOWN"
	}
	return strings.TrimSpace(string(output))
}

func GetGitTag() string {
	cmd := exec.Command("git", "describe", "--tags", "--abbrev=0")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return "UNKNOWN"
	}
	return strings.TrimSpace(out.String())
}
